﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Be.Windows.Forms;

namespace GemWorkshop.Hex
{
    public partial class HexEditor : Form
    {
        private string path;
        //private byte[] buffer;
        //private int bufferOffset;
        
        public HexEditor(string file)
        {
            InitializeComponent();
            path = file;
            //buffer = File.ReadAllBytes(file);
            //bufferOffset = 0;
            //vScrollBar1.Maximum = (buffer.Length - 1) / 8;

            this.Text = "Hex Editor - " + Path.GetFileName(file);

            hexBox1.ByteProvider = new DynamicFileByteProvider(path);

            //Goto(0);
        }

        #region Toolbar

        private void bSave_Click(object sender, EventArgs e)
        {
            ((DynamicFileByteProvider)hexBox1.ByteProvider).ApplyChanges();
        }

        private void bCross_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void bGoto_Click(object sender, EventArgs e)
        {
            hexBox1.Select(int.Parse(tOffset.Text, System.Globalization.NumberStyles.HexNumber), 0);
        }

        private void tOffset_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (IsHexChar(e.KeyChar))
            {
                // Uppercase hex digits
            }
            else if (e.KeyChar == '\b')
            {
                // Backspace okay
            }
            else
            {
                e.Handled = true;
            }
        }

        #endregion

        private bool IsHexChar(char c)
        {
            if (char.IsDigit(c)) return true;
            else if ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) return true;
            return false;
        }
    }
}
